package com.thd.springboottest.s3.utils;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {

    /**
     * 将file转为byte[]
     *
     * @param file
     * @return byte[]
     */
    public static byte[] file2Byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * byte[]转file
     *
     * @param buf
     * @param filePath
     * @param fileName void
     */
    public static File byte2File(byte[] buf, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return String
     */
    public static String getPrefix(String fileName) {
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        prefix = prefix.toLowerCase();
        return prefix;
    }


    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * inputStream转file
     *
     * @param is
     * @param filePath
     * @throws Exception void
     */
    public static void input2File(InputStream is, String filePath) throws Exception {
        FileOutputStream fos = null;
        try {
            // 打开一个已存在文件的输出流
            fos = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 将输入流is写入文件输出流fos中
        int ch = 0;
        try {
            while ((ch = is.read()) != -1) {
                fos.write(ch);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            //关闭输入流等（略）
            fos.close();
            is.close();
        }
    }

    /**
     * @param url 例子：http://demo.com/de3204c703de47e7b2552d927d172dc8.pdf  、
     * @return
     */
    public static String getFileName(String url) {

        String fileName = "";

        try {
            url = url.replaceAll("\\\\", "/");
            String[] urls = url.split("\\/");
            fileName = urls[urls.length - 1].split("\\.")[0];
        } catch (Exception e) {
            // TODO: handle exception
            fileName = "地址格式不正确";
        }

        return fileName;
    }

    /**
     * 通过阿里去URL获取文件名
     *
     * @param url
     * @return String
     */
    public static String getFileNameByUrl(String url) {
        //需要啥后缀自己加
        String suffixes = "avi|mpeg|3gp|mp3|mp4|wav|jpeg|gif|jpg|png|apk|exe|pdf|rar|zip|docx|doc|txt";
        Pattern pat = Pattern.compile("/([^</]+)[\\.](" + suffixes + ")");//正则判断
        Matcher mc = pat.matcher(url);//条件匹配
        while (mc.find()) {
            String substring = mc.group();//截取文件名后缀名
            return substring.replaceAll("/", "");
        }
        return null;
    }

}
